package org.smart4j.chapter1.proxy;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;

/**
 * @ClassName:
 * @Description: 切面代理
 * @Author: LynnZou
 * @Date: 2017/5/27
 */
public abstract class AspectProxy implements Proxy{

    private static final Logger LOGGER = LoggerFactory.getLogger(AspectProxy.class);

    @Override
    public Object doProxy(ProxyChain proxyChian) throws Throwable {
        Object result = null;

        Class<?> cls = proxyChian.getTargetClass();
        Method method = proxyChian.getTargetMethod();
        Object[] params = proxyChian.getMethodParams();

        begin();
        try{
            if(intercept(cls,method,params)){
                before(cls,method,params);
                result = proxyChian.doProxyChain();
                after(cls,method,params,result);
            }else{
                result = proxyChian.doProxyChain();
            }
        }catch (Exception e){
            LOGGER.error("proxy failure",e);
            error(cls,method,params,e);
            throw e;
        }finally {
            end();
        }
        return result;
    }

    public boolean intercept(Class<?> cls,Method method,Object[] params)throws Throwable {
        return true;
    }

    public void before(Class<?> cls,Method method,Object[] params) throws Throwable{}

    public void after(Class<?> cls,Method method,Object[] params,Object result) throws Throwable {}

    public void error(Class<?> cls,Method method,Object[] params,Throwable e){}

    public void begin(){}

    public void end(){}

}
